<style lang="less">
  @import '../styles/common.less';
</style>

<template>
  <div class="HeightAlldiv">
    <Row :gutter="10" class="row">
      <Card>
        <div class="HeightAlldiv-div" id="HeightAlldiv-div">
          <!-- 创建文本编辑器 -->
          <div id="editor-div" :style="{height: ckEditorContHeight + 'px'}">
          </div>

          <input type="file" id="checkImg" style="display: none" accept="image/*" @change="addFile">

          <div class="Button-footer">
            <Button class="Button" type="info" @click="showModelFun">重新输入验证码</Button>
            <Button class="Button" type="primary" :disabled="disabled" @click="saveFun">保存</Button>
          </div>
        </div>
      </Card>
    </Row>

    <Modal v-model="showModel" :closable=false :mask-closable=false :width="600"
           class="Modal-Detail-div" class-name="vertical-center-modal">
      <h3 slot="header" style="color:#2D8CF0">输入验证码</h3>
      <Form label-position="top">
        <FormItem label="验证码">
          <Input v-model.trim="code" placeholder="请输入验证码"></Input>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" :loading="saveLoading" @click="getDataByCode">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<style>
  #editor-div {
    overflow-y: auto;
  }

  #editor-div.ql-container, #editor-div .ql-editor {
    height: auto;
  }

  .Button-footer {
    width: 100%;
    height: 40px;
    text-align: right;
    line-height: 38px;
    padding-top: 10px;
  }

  .Button-footer .Button {
    margin-right: 10px;
  }
</style>
<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import Nim from '../../libs/mod.nim';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';


  export default {
    components: {},
    data () {
      return {
        ckEditorContHeight: 350,
        editorOption: null,

        saveLoading: false,
        showModel: true,
        code: '',
        disabled: true,
        dataObj: {},
        content: '',
      };
    },
    computed: {},
    beforeMount: function () {
      var _this = this;
    },
    beforeDestroy: function () {
      var _this = this;
    },
    created: function () {
      var _this = this;
    },
    mounted: function () {
      var _this = this;
      _this.init();
      _this.checkLeave();
    },
    methods: {
      checkLeave: function () {
        var _this = this;
        window.onbeforeunload = function (e) {
          var e = window.event || e;
          e.returnValue = ("确定离开当前页面吗？");
        }
      },
      saveFun: function () {
        var _this = this;
        var content = _this.editorOption ? _this.editorOption.container.firstChild.innerHTML : '';
        if (content) {
          _this.content = (content == '<p>&nbsp;</p>' || content == '<p><br></p>') ? '' : content;
        }
        if (_this.content == '') {
          Utils.showToast.error(_this, '请输入内容!');
          return false;
        }
        var dataObj = _this.dataObj;
        dataObj.content = _this.content; // 富文本
        var url = dataObj.url; // 地址
        if (url == '') {
          Utils.showToast.error(_this, '地址参数错误!');
          return false;
        }
        let params = {
          url: url,
          type: Util.method.post,
          data: dataObj,
          success: _successFun,
        };
        Util.ajax(_this, params);

        function _successFun(res) {
          if (res.result == 0) {
            _this.dataObj = {};
            _this.content = '';
            _this.setEditorOption();
            _this.disabled = true;
            _this.deleteFun();
            Utils.showToast.success(_this, '保存成功!');
          } else {
            Utils.showToast.error(_this, '保存失败!');
          }
        }

      },
      // 获取数据
      getDataByCode: function () {
        var _this = this;
        var code = _this.code;
        if (code == '') {
          Utils.showToast.error(_this, '请输入验证码!');
          return false;
        }
        var data = {
          code: code,
        };
        let params = {
          url: '/reditor/query',
          type: Util.method.post,
          data: data,
          success: _successFun,
        };
        Util.ajax(_this, params);

        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || {};
            var content = _data.content || '';
            var data = _data.data || '';
            var dataObj = {};
            if (data) {
              dataObj = Utils.toJson(data);
            }
            _this.dataObj = dataObj;
            _this.content = content;
            _this.setEditorOption();

            _this.disabled = false;
            _this.showModel = false;
          } else {
            _this.dataObj = {};
            _this.content = '';
            _this.setEditorOption();
            _this.disabled = true;
            Utils.showToast.error(_this, '查询失败，请确认验证码是否正确');
          }
        }
      },
      // 显示验证码弹窗
      showModelFun: function () {
        var _this = this;
        _this.code = '';
        _this.showModel = true;
      },
      // 设置富文本内容
      setEditorOption: function () {
        var _this = this;
        if (_this.editorOption) {
          _this.editorOption.container.firstChild.innerHTML = _this.content;
        } else {
          _this.init();
        }
      },
      // 初始化富文本
      init: function () {
        var _this = this;
        this.$nextTick(() => {
          var ckEditorContHeight = parseInt($('#HeightAlldiv-div').height()) - 44 - 80;
          _this.ckEditorContHeight = ckEditorContHeight;

//          var BackgroundClass = Quill.import('attributors/class/background');
//          var ColorClass = Quill.import('attributors/class/color');
//          var SizeStyle = Quill.import('attributors/style/size');
//          Quill.register(BackgroundClass, true);
//          Quill.register(ColorClass, true);
//          Quill.register(SizeStyle, true);

          var toolbarOptions = [
            ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
            ['blockquote', 'code-block'],
            [{'header': [1, 2, 3, 4, 5, 6, false]}],
            [{'header': 1}, {'header': 2}],               // custom button values
            [{'list': 'ordered'}, {'list': 'bullet'}],
//          [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
//          [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
//          [{'direction': 'rtl'}],                         // text direction
//          [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
//          [{'color': []}, {'background': []}],          // dropdown with defaults from theme
//          [{'font': []}],
            [{'align': []}],
            ['image', 'clean']                            // remove formatting button
          ];

          _this.editorOption = new Quill('#editor-div', {
            modules: {
              toolbar: toolbarOptions,
            },
            placeholder: '编辑内容...',
            theme: 'snow' // bubble snow
          });

          if (_this.content) {
            _this.editorOption.container.firstChild.innerHTML = _this.content;
          }

          let toolbar = _this.editorOption.getModule('toolbar');
          toolbar.addHandler('image', () => {
            document.getElementById('checkImg').click();
          });

          $('#editor-div .ql-editor').css('minHeight', ckEditorContHeight - 10 + 'px');
        });

      },
      // 上传图片
      addFile: function () {
        let _this = this;
        let inputObj = document.getElementById('checkImg');
        let fileObj = inputObj.files[0];
        if (typeof (fileObj) == "undefined" || fileObj.size <= 0) {
          Utils.showToast.error(_this, '请选择图片!');
          return false;
        }
        let fileName = fileObj.name;
        let fileTypeStr = fileObj.type;
        let fileTypeArr = fileTypeStr.split('/');
        let fileType = fileTypeArr[0].trim();
        let to_url = '';
        if (fileType == 'image') {
          to_url = '/file/addImage';
        } else {
          to_url = '/file/addFile';
        }
        let formFile = new FormData();
        formFile.append("file", fileObj); //加入文件对象
        let params = {
          url: to_url,
          type: Util.method.post,
          data: formFile,
          success: _successFileUpload,
        };
        Util.ajax(_this, params);

        function _successFileUpload(res) {
          let resData = res.data ? res.data : null;
          if (resData != undefined && resData != null && resData != '') {
            var urlp = resData.urlp;
            const range = _this.editorOption.getSelection();
            if (range) {
              _this.editorOption.insertEmbed(range.index, 'image', urlp);
            }
          }
        }
      },
      // 删除
      deleteFun: function () {
        var _this = this;
        var code = _this.code;
        if (!code) {
          return false;
        }
        var data = {
          code: code,
        };
        let params = {
          url: '/reditor/delete',
          type: Util.method.post,
          data: data,
          success: _successFun,
        };
        Util.ajax(_this, params);

        function _successFun(res) {
          if (res.result == 0) {
          }
        }
      },

    }
  }
  ;
</script>

<style>

</style>
